package glossos.parsing;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;

/** 
 * A Reader that reads all files in the specified directory, given a (optional) filter for file names.
 * At the end of each file, the method read() returns a '.' character, to indicate a sentence delimiter. 
 * The one exception to this rule is the last file. In that case, the last character returned will be the
 * last character itself. 
 * @author Otavio Macedo
 *
 */
public class CorpusReader extends Reader {
	private static Logger logger = Logger.getLogger(CorpusReader.class);

	private final Iterator<Reader> iterator;
	private Reader currentReader;
	
	public CorpusReader(Iterator<Reader> iterator) {
		this.iterator = iterator;
	}

	@Override
	public void close() throws IOException {
		if (currentReader != null)
			currentReader.close();
	}

	@Override
	public int read() throws IOException {
    	char cb[] = new char[1];
    	int number = read(cb, 0, 1);
		if (number == -1)
    	    return -1;
		else if (number == -2)
			return '.';
    	else
    	    return cb[0];
    }

	@Override
	public int read(char[] cbuf, int off, int len) throws IOException {
		if (currentReader == null){
			if (iterator.hasNext())
				currentReader = iterator.next();
		}
		
		int number = currentReader.read(cbuf, off, len);

		while(number == -1){
			currentReader.close();
			if (iterator.hasNext()){
				currentReader = iterator.next();
				number = -2;
			} else {
				break;
			}
		}
		return number;
	}
	

}
